import React, { useRef, useState } from 'react';
import { history } from 'umi';
import {
  Form,
  Input,
  Button,
  Checkbox,
  Tabs,
  message,
  validateMessages,
} from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { login } from '../../apis';
import qs from 'query-string';
import storage from '../../utils/storageUtils';
import styles from './login.less';
import { check } from '../../apis';

const { TabPane } = Tabs;

export default function Login() {
  const username = useRef();
  const onFinish = async (values) => {
    const user = qs.stringify({
      username: values.username,
      password: values.password,
    });
    const result = await login(user);
    if (result.data) {
      storage.setStorage('token', result.data.token);
      storage.setStorage('userInfo', result.data.user);
      history.push('/home');
      message.success('登录成功');
    } else {
      message.error('用户名或密码错误');
    }
  };
  const checkValue = async (rule, value, callback) => {
    if (value) {
      const result = await check(value);
      if (result) {
        return Promise.reject('用户未注册');
      } else {
        return Promise.resolve();
      }
    } else {
      return Promise.reject('用户名不能为空!');
    }
  };
  return (
    <div className={styles.login_box}>
      <Form
        name="normal_login"
        className="login-form"
        initialValues={{ remember: true }}
        onFinish={onFinish}
      >
        <Tabs defaultActiveKey="1">
          <TabPane tab="账户密码登录" key="1">
            <Form.Item
              name="username"
              rules={[
                {
                  // required: true, message: '用户名不能为空!'
                },
                {
                  validator: checkValue,
                },
              ]}
            >
              <Input
                prefix={<UserOutlined className="site-form-item-icon" />}
                placeholder="用户名"
              />
            </Form.Item>
            <Form.Item
              name="password"
              rules={[{ required: true, message: '密码不能为空!' }]}
            >
              <Input
                prefix={<LockOutlined className="site-form-item-icon" />}
                type="password"
                placeholder="密码"
              />
            </Form.Item>
            <Form.Item>
              <Form.Item name="remember" valuePropName="checked" noStyle>
                <Checkbox>记住密码</Checkbox>
              </Form.Item>

              <a className="login-form-forgot" href="">
                忘记密码了?
              </a>
            </Form.Item>
          </TabPane>
          <TabPane tab="手机号登录" key="2">
            暂未开放
          </TabPane>
        </Tabs>
        <Button type="primary" htmlType="submit" className={styles.login_btn}>
          登录
        </Button>
        <div className={styles.entrance}>
          <a href="">注册</a>
          <a href="">商家入驻</a>
        </div>
      </Form>
    </div>
  );
}
